import { messages } from 'share/common';
import React from 'react';
import menuRoute from 'routes/menuRoute';
import config from 'config';
import { Form, Col, Badge, Button, Table, Checkbox, message, Icon } from 'antd';
import contractService from 'containers/setting/contract-type-define/contract-type-define.service';
import ListSelector from 'components/list-selector';
import ResizeTable from "components/resize-table";

class CompanyDistribution extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      companyTypeList: [
        { label: messages('adjust.setOfBooks'), id: 'setOfBooksCode' },
        { label: messages('contract.type.code'), id: 'contractTypeCode' },
        { label: messages('contract.type.name'), id: 'contractTypeName' },
        { label: messages('contract.type.status'), id: 'isEnabled' }
      ],
      companyTypeInfo: {},
      columns: [
        { title: messages('supplier.company.code'), dataIndex: 'companyCode' },
        { title: messages('supplier.company.name'), dataIndex: 'companyName' },
        {
          title: messages('supplier.company.type'),
          dataIndex: 'companyTypeName',
          render: type => <span>{type ? type : '-'}</span>
        },
        {
          title: messages('common.enabled'),
          dataIndex: 'isEnabled',
          width: '8%',
          render: (isEnabled, record) => <Checkbox defaultChecked={isEnabled} onChange={(e) => this.handleStatusChange(e, record)}/>
        }
      ],
      data: [],
      pagination: {
        total: 0
      },
      page: 0,
      pageSize: 10,
      showListSelector: false,
      selectorItem: {},
      contractTypeDefine: menuRoute.getRouteItem('contract-type-define', 'key'),    //合同类型定义
    };
  }

  componentDidMount() {
    this.getBasicInfo();
    this.getList();
  }

  getBasicInfo = () => {
    const { params } = this.props;
    contractService.getContractTypeInfo(params.setOfBooksId, params.id, { roleType: 'TENANT' })
      .then((res) => {
        let selectorItem = {
          title: messages('budget.item.batchCompany'),
          url: `${config.contractUrl}/api/contract/type/${params.setOfBooksId}/companies/query/filter`,
          searchForm: [
            {
              type: 'input',
              id: 'companyCode',
              label: messages('supplier.company.code')
            },
            {
              type: 'input',
              id: 'companyName',
              label: messages('supplier.company.name')
            },  //公司名称
            {
              type: 'input',
              id: 'companyCodeFrom',
              label: messages('chooser.data.companyCode.from'/*公司代码从*/)
            },
            {
              type: 'input',
              id: 'companyCodeTo',
              label: messages('chooser.data.companyCode.to'/*公司代码至*/)
            }
          ],
          columns: [
            {
              title: messages('supplier.company.code'),
              dataIndex: 'code'
            },
            {
              title: messages('supplier.company.name'),
              dataIndex: 'name'
            },
            {
              title: messages('supplier.company.type'),
              dataIndex: 'attribute4',
              render: value => value || '-'
            }
          ],
          key: 'id'
        };
        this.setState({ companyTypeInfo: res.data, selectorItem });
      });
  };

  getList = () => {
    const { params } = this.props;
    const { page, pageSize } = this.state;
    this.setState({ loading: true });
    contractService.getCompanyDistributionByContractType(page, pageSize, params.setOfBooksId, params.id)
      .then((res) => {
        if (res.status === 200) {
          this.setState({
            data: res.data,
            loading: false,
            pagination: {
              total: Number(res.headers['x-total-count']) ? Number(res.headers['x-total-count']) : 0,
              current: page + 1,
              onChange: this.onChangePaper,
              showTotal: total => messages('common.total', { total: `${total}` })
            }
          });
        }
      });
  };

  onChangePaper = (page) => {
    if (page - 1 !== this.state.page) {
      this.setState({ page: page - 1 }, () => {
        this.getList();
      });
    }
  };

  handleStatusChange = (e, record) => {
    let params = {
      id: record.id,
      isEnabled: e.target.checked,
      versionNumber: record.versionNumber
    };
    contractService.updateCompanyDistributionStatus(this.props.params.setOfBooksId, params)
      .then((res) => {
        if (res.status === 200) {
          this.getList();
          message.success(messages('common.operate.success'));
        }
      })
      .catch(e => {
        message.error(`${messages('common.operate.filed')}，${e.response.data.message}`);
      });
  };

  handleListShow = (flag) => {
    this.setState({ showListSelector: flag });
  };

  handleListOk = (values) => {
    const { params } = this.props;
    let paramsValue = {};
    paramsValue.contractTypeId = this.props.params.id;
    paramsValue.companyIds = [];
    values.result.map(item => {
      paramsValue.companyIds.push(item.id);
    });
    contractService.distributionCompany(params.setOfBooksId, paramsValue)
      .then((res) => {
        if (res.status === 200) {
          message.success(messages('common.operate.success'));
          this.handleListShow(false);
          this.getList();
        }
      })
      .catch((e) => {
        if (e.response) {
          message.error(`${messages('common.operate.filed')}，${e.response.data.message}`);
        }
      });
  };

  handleBack = () => {
    this.context.router.push(this.state.contractTypeDefine.url);
  };

  render() {
    const { loading, companyTypeList, companyTypeInfo, columns, data, showListSelector, selectorItem } = this.state;
    let periodRow = [];
    let periodCol = [];
    companyTypeList.map((item, index) => {
      index <= 2 && periodCol.push(
        <Col span={6} style={{ marginBottom: '15px' }} key={item.id}>
          <div style={{ color: '#989898' }}>{item.label}</div>
          <div style={{ wordWrap: 'break-word' }}>
            {item.id === 'setOfBooksCode' ?
              companyTypeInfo[item.id] ? companyTypeInfo[item.id] + ' - ' + companyTypeInfo.setOfBooksName : '-' :
              companyTypeInfo[item.id]}
          </div>
        </Col>
      );
      if (index === 2) {
        periodRow.push(
          <Col
            style={{ background: '#f7f7f7', padding: '20px 25px 0', borderRadius: '6px 6px 0 0' }}
            key="1">
            {periodCol}
          </Col>
        );
      }
      if (index === 3) {
        periodRow.push(
          <Col span={6} style={{ marginBottom: '15px' }} key={item.id}>
            <div style={{ color: '#989898' }}>{item.label}</div>
            <Badge status={companyTypeInfo[item.id] ? 'success' : 'error'}
                   text={companyTypeInfo[item.id] ? messages('common.enabled') : messages('common.disabled')}/>
          </Col>
        );
      }
    });
    return (
      <div className="company-distribution">
        <div className="jsq"
             style={{ background: '#f5f5f5', width: '100%', height: '80', borderRadius: '4' }}>
          {periodRow}
        </div>
        <div className="table-header">
          <div className="table-header-buttons">
            <Button type="primary" loading={showListSelector}
                    onClick={() => this.handleListShow(true)}>{messages('budget.item.batchCompany')/*批量分配公司*/}</Button>
          </div>
        </div>
        <ResizeTable
          rowKey={record => record.companyId}
          columns={columns}
          dataSource={data}
          loading={loading}
          bordered
          size="middle"
        />
        <ListSelector visible={showListSelector}
                      onCancel={() => this.handleListShow(false)}
                      selectorItem={selectorItem}
                      extraParams={{ contractTypeId: this.props.params.id }}
                      onOk={this.handleListOk}/>
        <a style={{ fontSize: '14px', paddingBottom: '20px' }} onClick={this.handleBack}><Icon
          type="rollback" style={{ marginRight: '5px' }}/>{messages('common.back')/*返回*/}</a>
      </div>
    );
  }
}

CompanyDistribution.contextTypes = {
  router: React.PropTypes.object
};

const wrappedCompanyDistribution = Form.create()(CompanyDistribution);

export default wrappedCompanyDistribution;
